<?php
// +----------------------------------------------------------------------
// | LikeShop100%开源免费商用电商系统
// +----------------------------------------------------------------------
// | 欢迎阅读学习系统程序代码，建议反馈是我们前进的动力
// | 开源版本可自由商用，可去除界面版权logo
// | 商业版本务必购买商业授权，以免引起法律纠纷
// | 禁止对系统程序代码以任何目的，任何形式的再发布
// | Gitee下载：https://gitee.com/likeshop_gitee/likeshop
// | 访问官网：https://www.likemarket.net
// | 访问社区：https://home.likemarket.net
// | 访问手册：http://doc.likemarket.net
// | 微信公众号：好象科技
// | 好象科技开发团队 版权所有 拥有最终解释权
// +----------------------------------------------------------------------

// | Author: LikeShopTeam
// +----------------------------------------------------------------------
namespace app\api\logic;

use app\api\model\User;
use app\common\logic\LogicBase;
use app\common\logic\NoticeLogic;
use app\common\model\AccountLog;
use app\common\model\AfterSale;
use app\common\model\Order;
use app\common\server\ConfigServer;
use app\common\server\WeChatServer;
use EasyWeChat\Factory;
use EasyWeChat\Kernel\Exceptions\Exception;
use think\Db;

class UserLogic extends LogicBase
{
    public static function center($user_id)
    {
        $user = User::get($user_id);
        //待审核
        $user->wait_pay = Db::name('order')->where(['del' => 0, 'user_id' => $user_id, 'order_status' => Order::WAIT_AUDIT])->count();
        //待对方审核
        $user->wait_delivery = Db::name('order')->where(['del' => 0, 'user_id' => $user_id, 'order_status' => [Order::PLATFORM_AUDIT]])->count();
        //待主播开播审核
        $user->wait_take = Db::name('order')->where(['del' => 0, 'user_id' => $user_id, 'order_status' => [Order::PLAY_AUDIT]])->count();
//        //待评论
//        $user->wait_comment = Db::name('order o')
//            ->join('order_goods og','o.id = og.order_id')
//            ->where(['del'=>0,'user_id'=>$user_id,'order_status'=>Order::STATUS_FINISH,'is_comment'=>0])
//            ->count('og.id');
        //售后中
//        $user->after_sale = Db::name('after_sale')
//            ->where(['del'=>0,'user_id'=>$user_id])
//            ->where('status','<>',AfterSale::STATUS_SUCCESS_REFUND)
//            ->count();
//        $user->coupon = Db::name('coupon_list')->where(['user_id'=>$user_id,'del'=>0,'status'=>0])->count();

        //消息数量
//        $user->notice_num = NoticeLogic::unRead($user_id) ? 1 : 0;
//        //下个会员等级提示
//        $user_level = Db::name('user_level')
//            ->where([
//                ['id','>',$user->getData('level')],
//                ['del','=',0]
//            ])->order('growth_value asc')
//            ->find();
//        $user['next_level_tips'] = '';
//        if($user_level){
//            $user['next_level_tips'] = '距离升级还差'.intval($user_level['growth_value'] - $user['user_growth']);
//        }
        $user->visible(['id', 'nickname', 'sn', 'avatar', 'next_level_tips', 'user_money', 'total_order_amount', 'total_recharge_amount',
            'coupon', 'user_integral', 'level', 'wait_pay', 'wait_take', 'wait_delivery',
            'wait_comment', 'after_sale', 'notice_num']);

        return $user;
    }

    public static function accountLog($user_id, $source, $type, $page, $size)
    {
        $source_type = '';
        $where[] = ['user_id', '=', $user_id];
        switch ($source) {
            case 1:
                $source_type = AccountLog::money_change;
                break;
            case 2:
                $source_type = AccountLog::integral_change;
                break;
            case 3:
                $source_type = AccountLog::growth_change;

        }
        $where[] = ['source_type', 'in', $source_type];
        if ($type) {
            $where[] = ['change_type', '=', $type];
        }
        $accountLog = new AccountLog();
        $count = $accountLog
            ->where($where)
            ->count();
        $list = $accountLog
            ->where($where)
            ->page($page, $size)
            ->order('id desc')
            ->field('id,change_amount,source_type,change_type,create_time')
            ->select();
        $more = is_more($count, $page, $size);  //是否有下一页

        $data = [
            'list' => $list,
            'page_no' => $page,
            'page_size' => $size,
            'count' => $count,
            'more' => $more
        ];
        return $data;
    }

    //获取用户信息
    public static function getUserInfo($user_id)
    {
        $info = User::where(['id' => $user_id])
            ->field('nickname,avatar,mobile,sex')
            ->find();
        return $info;
    }

    //设置个人信息
    public static function setUserInfo($user_id, $post)
    {
        $data = [
            'nickname' => $post['nickname'],
            'sex' => $post['sex'] ? intval($post['sex']) : 0,
            'avatar' => $post['avatar'],
            'remark' => $post['remark'] ?? "",
        ];
        $res = Db::name('user')
            ->where(['id' => $user_id])
            ->update($data);
        return $res;
    }


    //修改手机号
    public static function changeMobile($user_id, $data)
    {
        $user = User::get($user_id);
        $user->mobile = $data['new_mobile'];
        $user->save();
        return $user;
    }


    //获取微信手机号
    public static function getMobileByMnp($post)
    {
        try {
            $config = WeChatServer::getMnpConfig();
            $app = Factory::miniProgram($config);
            $response = $app->auth->session($post['code']);
            if (!isset($response['session_key'])) {
                throw new Exception();
            }
            $response = $app->encryptor->decryptData($response['session_key'], $post['iv'], $post['encrypted_data']);
            return self::dataSuccess('', $response);
        } catch (Exception $e) {
            return self::dataError('失败:' . $e->getMessage());
        }
    }


    public static function myWallet($user_id)
    {
        $info = Db::name('user')
            ->where(['id' => $user_id])
            ->field('user_money,total_order_amount,total_recharge_amount,user_growth')
            ->find();
        $info['open_racharge'] = ConfigServer::get('recharge', 'open_racharge', 0);
        return $info;
    }

    //更新微信信息
    public static function updateWechatInfo($user_id, $post)
    {
        Db::startTrans();
        try {
            $time = time();
            $avatar_url = $post['avatar'];
            $nickanme = $post['nickname'];
            $sex = $post['sex'];

            $config = [
                'default' => ConfigServer::get('storage', 'default', 'local'),
                'engine' => ConfigServer::get('storage_engine')
            ];
            $avatar = ''; //头像路径
            if ($config['default'] == 'local') {
                $file_name = md5($user_id . $time . rand(10000, 99999)) . '.jpeg';
                $avatar = download_file($avatar_url, 'uploads/user/avatar/', $file_name);
            } else {
                $avatar = 'uploads/user/avatar/' . md5($user_id . $time . rand(10000, 99999)) . '.jpeg';
                $StorageDriver = new StorageDriver($config);
                if (!$StorageDriver->fetch($avatar_url, $avatar)) {
                    throw new Exception('头像保存失败:' . $StorageDriver->getError());
                }
            }

            $user = new User;
            $user->save([
                'nickname' => $nickanme,
                'avatar' => $avatar,
                'sex' => $sex
            ], ['id' => $user_id]);

            Db::commit();
            return true;

        } catch (\Exception $e) {
            Db::rollback();
            return $e->getMessage();
        }
    }

    /**
     * 获取用户信息
     * @param $user_id
     * @return array|false|mixed|\PDOStatement|string|\think\Collection|Db[]|\think\db\Query[]
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getUserMsg($user_id)
    {
        return Db::name("user_msg")->where("to_user", $user_id)->order("create_time desc")->select();
    }

    /**
     * 用户消息已读
     * @param $user_id
     * @param $id
     * @return false|int|string
     * @throws \think\Exception
     * @throws \think\db\exception\DbException
     * @throws \think\exception\PDOException
     */
    public static function msgIsRead($user_id, $id)
    {
        return Db::name("user_msg")->where(["to_user" => $user_id, "id" => $id])->data(["is_read" => 1])->update();
    }

    /**
     *
     * @param $user_id
     * @return array|false|mixed|null|\PDOStatement|string|Db|\think\db\Query|\think\Model
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getUsrtExamine($user_id)
    {
        $isRole = LoginLogic::isRole($user_id);

        $result = [];
        if ($isRole['role'] == 1) {
            $result = Db::name('the_host')->where(['user_id' => $user_id])->find();
        }
        if ($isRole['role'] == 2) {
            $result = Db::name('supplier')->where(['user_id' => $user_id])->find();
        }
        if (!empty($result) && $result['status'] == 3) {
            $where[] = $isRole['role'] == 1 ? ["type", '=', 2] : ["type", '=', 4];
            $where[] = ["to_user", '=', $result['user_id']];
            $result['examine_type'] = Db::name("user_log_copy")
                ->where($where)
                ->field("id,title,content,to_user,create_time")
                ->order("id desc")
                ->find();
        }
        return $result;
    }

    //添加收藏记录
    public static function setUsrtCollection($data, $user_id)
    {
        $installData = [];
        foreach ($data as $key => $value) {
            $installData[$key]['collection_id'] = $value;
            $installData[$key]['type'] = 0;
            $installData[$key]['user_id'] = $user_id;
            $installData[$key]['create_time'] = time();
        }


        return Db::name('user_collection')->insertall($installData);
    }

    //是否有过收藏记录
    public static function getUsrtCollectionInfo($data, $user_id, $type = 0)
    {
        return Db::name('user_collection')->where(['collection_id' => $data['collection_id'], 'user_id' => $user_id, "type" => $type])->find();
    }

    //用户收藏记录
    public static function getUsrtCollection($type, $user_id, $page_no, $page_size)
    {

        //商品收藏
        if ($type == 0) return Db::name('user_collection')
            ->alias("uc")
            ->leftjoin('goods g', 'uc.collection_id = g.id')
            ->field('g.*,uc.id as collection_id')
            ->page($page_no, $page_size)
            ->select();

        //主播收藏
        if ($type == 1) return Db::name('user_collection')
            ->alias("uc")
            ->leftjoin('the_host g', 'uc.collection_id = g.id')
            ->field('g.*,uc.id as collection_id')
            ->page($page_no, $page_size)
            ->select();

        //商户收藏
        if ($type == 2) return Db::name('user_collection')
            ->alias("uc")
            ->leftjoin('supplier g', 'uc.collection_id = g.id')
            ->field('g.*,uc.id as collection_id')
            ->page($page_no, $page_size)
            ->select();
    }

    //用户取消收藏
    public static function delUsrtCollection($data, $user_id)
    {
        return Db::name('user_collection')->where(['collection_id' => $data['collection_id'], 'user_id' => $user_id, 'type' => $data['type']])->delete();
    }

    //用户收藏goods_id_list
    public static function userCollectionList($user_id)
    {
        return Db::name('user_collection')->where(['user_id' => $user_id, 'type' => 0])->column('collection_id');
    }

    //主播带货标签高于同比
    public static function userHigherThanYear($host_id)
    {
        //返回数据
        $return_data = [];
        //获取已完成的档期订单
        $order_list = Db::name('order')
            ->alias("o")
            ->leftjoin('schedule s', 'o.schedule_id = s.id')
            ->where(['o.order_status' => 6, 's.schedule_status' => 6])
            ->column('o.host_id', 'o.id');

        if ($order_list) {
            //将主播的订单取出
            $host_order = [];
            foreach ($order_list as $key => $value) {
                if ($value == $host_id) {
                    $host_order[] = $key;
                }
            }
            //获取主播已完成的档期商品 按照一级分类统计
            $host_order_goods_list = Db::name('order_goods')
                ->alias("o")
                ->field('g.first_category_id ,count(1) as host_first_category_num,gc.name as category_name')
                ->leftjoin('goods g', 'g.id = o.goods_id')
                ->leftjoin('goods_category gc', 'g.first_category_id = gc.id')
                ->where(['order_id' => $host_order])
                ->group('g.first_category_id')
                ->select();
            //var_dump($host_order_goods_list);die;
            //获取分类下的商品数量
            $order_goods_list = Db::name('order_goods')
                ->alias("o")
                ->leftjoin('goods g', 'g.id = o.goods_id')
                ->field('g.first_category_id,count(1) as host_first_category_num')
                ->where(['o.order_id' => array_keys($order_list), 'g.first_category_id' => array_column($host_order_goods_list, 'first_category_id')])
                ->group('g.first_category_id')
                ->select();

            //根据类型进行比例分组
            foreach ($host_order_goods_list as $key => $value) {
                if ($order_goods_list[$key]['first_category_id'] == $value['first_category_id']) {
                    $return_data[$value['first_category_id']]['host_count'] = $value['host_first_category_num'];
                    $return_data[$value['first_category_id']]['count'] = $order_goods_list[$key]['host_first_category_num'];
                }

            }
        }

        $seven_day_sql = 'SELECT
    a.statis_date AS statis_date,
    IFNULL(count(b.id), 0) AS num
FROM
    (
        SELECT
            *
        FROM
            (
                SELECT
                    date_sub(curdate(), INTERVAL 1 DAY) AS statis_date
                UNION ALL
                    SELECT
                        date_sub(curdate(), INTERVAL 2 DAY) AS statis_date
                    UNION ALL
                        SELECT
                            date_sub(curdate(), INTERVAL 3 DAY) AS statis_date
                        UNION ALL
                            SELECT
                                date_sub(curdate(), INTERVAL 4 DAY) AS statis_date
                            UNION ALL
                                SELECT
                                    date_sub(curdate(), INTERVAL 5 DAY) AS statis_date
                                UNION ALL
                                    SELECT
                                        date_sub(curdate(), INTERVAL 6 DAY) AS statis_date
                                    UNION ALL
                                        SELECT
                                            date_sub(curdate(), INTERVAL 7 DAY) AS statis_date
            ) d
    ) a
LEFT JOIN mhw_schedule b ON a.statis_date = b. SCHEDULE and b.schedule_status = 6 and b.host_id = '.$host_id.'
GROUP BY
    a.statis_date
ORDER BY
    statis_date DESC';
        $seven_day = Db::query($seven_day_sql);

        return ['fan' => array_values($return_data), 'column' => $host_order_goods_list, 'sevenday' => $seven_day];

    }
}